/*
 * Copyright 2018 Zhenjie Yan.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yanzhenjie.andserver.util;


import com.yanzhenjie.andserver.http.multipart.MultipartFile;
import com.yanzhenjie.andserver.model.UserInfo;
import com.yanzhenjie.andserver.slice.MainAbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.app.Context;
import ohos.data.resultset.ResultSet;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by Zhenjie Yan on 2018/6/9.
 */
public class FileUtils {

    /**
     * Create a random file based on mimeType.
     *
     * @param file file.
     * @return file object.
     */
    public static File createRandomFile(MultipartFile file) {
        return new File(new MainAbilitySlice().getPath(), file.getFilename());
    }

    /**
     * SD is available.
     *
     * @param context 上下文
     * @return true otherwise is false.
     */
    public static boolean storageAvailable(Context context) {
        File sdDir = context.getDistributedDir();
        if (sdDir == null) {
            return false;
        }
        File sd = null;
        try {
            sd = new File(sdDir.getCanonicalPath());
        } catch (IOException e) {
            e.fillInStackTrace();
        }
        if (sd == null) {
         return false;
        }
        return sd.canWrite();
    }


    public static InputStream fileToinputstream(File file) {
        try {
            InputStream in = new FileInputStream(file);
            return in;
        } catch (FileNotFoundException e) {
            e.fillInStackTrace();
        }
        return null;
    }


    /**
     * 创建目录
     *
     * @param dir_path 创建路径
     */
    public static void mkDir(String dir_path) {
        File myFolderPath = new File(dir_path);
        try {
            boolean isPath = myFolderPath.exists();
            if (!isPath) {
                boolean pathDel = myFolderPath.mkdir();
                System.out.println("path delete " + pathDel);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    /**
     * 判断指定的文件是否存在。
     *
     * @param fileName
     * @return File(fileName).isFile() 返回布尔
     */
    public static boolean isFileExist(String fileName) {
        return new File(fileName).isFile();
    }

    /**
     * 得到文件后缀名
     *
     * @param fileName 文件名
     * @return fileNam 返回后缀名
     */
    public static String getFileExt(String fileName) {
        int point = fileName.lastIndexOf('.');
        int length = fileName.length();
        if (point == -1 || point == length - 1) {
            return "";
        } else {
            return fileName.substring(point + 1, length);
        }
    }

    /**
     * 删除文件夹及其下面的子文件夹
     *
     * @param dir dir
     * @throws IOException IOException
     */
    public static void deleteDir(File dir) throws IOException {

        File[] files = dir.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                boolean isFile = file.isFile();
                if (isFile) {
                    boolean fileDel = file.delete();
                    System.out.println("file delete " + fileDel);
                } else {
                    deleteDir(file);
                }
            }
        }

    }

    /**
     * 文件大小
     *
     * @param fileS 文件长度
     * @return fileSizeString 文件大小
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 复制文件
     *
     * @param src src
     * @param dst dst
     * @throws Exception Exception
     */
    public static void copy(File src, File dst) throws Exception {
        int BUFFER_SIZE = 4096;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
            out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.fillInStackTrace();
                }
                in = null;
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.fillInStackTrace();
                }
                out = null;
            }
        }
    }

    /**
     * 返回文件列表
     *
     * @param strPath strPath
     * @return filelist 文件列表
     */
    public static List<File> getSortFileList(String strPath) {
        List<File> filelist = new ArrayList<>();
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files.length != 0) {
            Arrays.sort(files, new Comparator<File>() {//按文件的修改日期递减排序
                public int compare(File f1, File f2) {
                    long diff = f1.lastModified() - f2.lastModified();
                    if (diff > 0)
                        return -1;
                    else if (diff == 0)
                        return 0;
                    else
                        return 1;
                }

            });


            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();

                if (files[i].isDirectory()) {
                    try {
                        getFileList(files[i].getCanonicalPath()); //遍历子文件夹里面的东西
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                } else if (fileName.endsWith("exe")) { // 以***结尾的文件
                    try {
                        String strFileName = files[i].getCanonicalPath();
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                    filelist.add(files[i]);
                } else {
                    filelist.add(files[i]);
                    continue;
                }
            }
        }

        return filelist;
    }

    /**
     * 返回文件列表
     *
     * @param strPath strPath
     * @return filelist filelist
     */
    public static List<File> getFileList(String strPath) {
        List<File> filelist = new ArrayList<>();
        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                System.out.println("pathss--" + fileName);
                if (files[i].isDirectory()) {
                    try {
                        getFileList(files[i].getCanonicalPath()); //遍历子文件夹里面的东西
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                } else if (fileName.endsWith("exe")) { // 以***结尾的文件
                    try {
                        String strFileName = files[i].getCanonicalPath();
                    } catch (IOException e) {
                        e.fillInStackTrace();
                    }
                    filelist.add(files[i]);
                } else {
                    filelist.add(files[i]);
                    continue;
                }
            }
        }
        return filelist;
    }

    public static String uriTopath(Uri contentUri, Context mContext) {
        String[] proj = {AVStorage.Images.Media.DATA};
        String picPath = "";
        DataAbilityHelper helper = DataAbilityHelper.creator(mContext);
        try {
            ResultSet result = helper.query(contentUri, proj, null);
            while (result != null && result.goToNextRow()) {
                int mediaId = result.getColumnIndexForName(AVStorage.Images.Media.DATA);
                picPath = result.getString(mediaId);
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return picPath;
    }

    public static int copySdcardFile(String fromFile, String toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return 0;
        } catch (Exception ex) {
            return -1;
        }
    }

    public static int copySdcardFile(InputStream fosfrom, String toFile) {
        try {
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return 0;
        } catch (Exception ex) {
            return -1;
        }
    }
}